﻿using System.Web.Mvc;
using System.Web.Security;
using BisinessLogic;
using Domain.Entities;
using Web.Models;
using Web.ViewModels;


namespace Web.Controllers
{
    public class AccountController : Controller
    {
        private DataManager dataManager;

        public AccountController(DataManager dataManager)
        {
            this.dataManager = dataManager;
        }

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                MigrateShoppingCart(model.UserName);
                if (dataManager.MembershipProvider.ValidateUser(model.UserName, model.Password))
                {
                 FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

                 if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1
                     && returnUrl.StartsWith("/")
                     && !returnUrl.StartsWith("//") &&
                     !returnUrl.StartsWith("/\\"))
                 {
                     return Redirect(returnUrl);
                 }
                    

                        return RedirectToAction("Index", "Home");
                }
                ModelState.AddModelError("", "Имя пользователя или пароль указаны неверно.");
            }

            return View(model);
        }

        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                   MembershipCreateStatus status = dataManager.MembershipProvider.CreateUser(
                    model.UserName, model.Password, model.Email,
                    model.FirstName, model.LastName, model.MiddleName,3);

                   MigrateShoppingCart(model.UserName);
               
                if (status == MembershipCreateStatus.Success)
                {
                    return View("Success");
                }
                ModelState.AddModelError("", GetMembershipCreateStatusResultText(status));
            }
            return View(model);
        }

        // Создаем текст ошибки для MembershipCreateStatus
        private string GetMembershipCreateStatusResultText(MembershipCreateStatus status)
        {
            if (status == MembershipCreateStatus.DuplicateEmail)
            {
                return "Пользователь с таким email  уже сушествует";
            }
            if (status == MembershipCreateStatus.DuplicateUserName)
            {
                return "Пользователь с таким логином  уже сушествует";
            }
            return "Неизвесная ошибка";
        }

          [Authorize]
        public ActionResult LogOut()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index");
        }
        [Authorize]
        public ActionResult Profile()
        {
             int currentUserId = (int)Membership.GetUser().ProviderUserKey;

            User user = dataManager.Users.GetUserById(currentUserId);
            ProfileModel prof = new ProfileModel
            {
                Login = user.Login,
                Address = user.Address,
                City = user.City,
                FirstName = user.FirstName,
                LastName = user.LastName,
                MiddleName = user.MiddleName,
                Phone = user.Phone,
                PostalCode = user.Phone,
                State = user.State
            };
            return View(prof);

        }
        [HttpPost]
        public ActionResult Profile(ProfileModel model)
        {
            if (ModelState.IsValid)
            {
                int currentUserId = (int)Membership.GetUser().ProviderUserKey;
                User user = dataManager.Users.GetUserById(currentUserId);

                user.Address = model.Address;
                user.City = model.City;
                user.FirstName = model.FirstName;
                user.LastName = model.LastName;
                user.MiddleName = model.MiddleName;
                user.Phone = model.Phone;
                user.PostalCode = model.PostalCode;
                user.State = model.State;

                dataManager.Users.SaveUser(user);

              return  RedirectToAction("Index", "Home");
            }

            return View(model);

        }



        private void MigrateShoppingCart(string UserName)
        {
            // Associate shopping cart items with logged-in user
            var cart = ShoppingCart.GetCart(this.HttpContext);

            cart.MigrateCart(UserName);
            Session[ShoppingCart.CartSessionKey] = UserName;
        }

    }
}
